package com.example.imgrecognition;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import com.cv4j.core.datamodel.CV4JImage;
import com.cv4j.core.datamodel.ImageProcessor;
import com.cv4j.core.hist.CalcHistogram;
import com.cv4j.core.hist.CompareHist;
import com.example.imgrecognition.Activity.TakePhotoActivity;
import com.example.imgrecognition.Model.Device;
import com.example.imgrecognition.Model.Msg;
import com.example.imgrecognition.Model.ParamModel;
import com.example.imgrecognition.Util.ToastUtil;
import com.zk.code.net.FileUtil;
import com.zk.code.net.NetUtil;

import org.litepal.crud.DataSupport;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class ImgCompareFreActivity extends Activity {
    private ArrayList<String> arrList;
    byte[] b ;
    String matchdegree = "0.88";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_img_compare_fre);
        MyApplication.getInstance().addActivity(this);
        arrList = getIntent().getStringArrayListExtra("list");
        int count = DataSupport.count(ParamModel.class);
        if(count>0) {
            ParamModel pm = DataSupport.findLast(ParamModel.class);
            if(!(pm.getMatchdegree()==null||pm.getMatchdegree().equals(""))){
                matchdegree = pm.getMatchdegree();
            }
        }else{
            matchdegree= "0.88";
        }
        b = getIntent().getByteArrayExtra("imgarr");
        ToastUtil.show(ImgCompareFreActivity.this,"前置摄像头图像对比");
        if(arrList!=null && arrList.size()>1){
            comparePic();
        }else{
            backToPre();
        }
    }

    private void  comparePic(){
        try{
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inSampleSize = 4;//直接设置它的压缩率，表示1/2
            Bitmap bitmap = BitmapFactory.decodeFile(arrList.get(0),options);
            CV4JImage cv4jImage = new CV4JImage(bitmap);
            ImageProcessor imageProcessor = cv4jImage.convert2Gray().getProcessor();
            int[][] source = null;
            int[][] target = null;
            CalcHistogram calcHistogram = new CalcHistogram();
            int bins = 180;
            source = new int[imageProcessor.getChannels()][bins];
            calcHistogram.calcHSVHist(imageProcessor,bins,source,true);
            Bitmap bitmapa = BitmapFactory.decodeFile(arrList.get(1),options);
            CV4JImage cv4jImagea = new CV4JImage(bitmapa);
            ImageProcessor imageProcessors = cv4jImagea.convert2Gray().getProcessor();
            target = new int[imageProcessors.getChannels()][bins];
            calcHistogram.calcHSVHist(imageProcessors,bins,target,true);
            CompareHist compareHist = new CompareHist();
//            StringBuilder sb = new StringBuilder();
//            sb.append("巴氏距离:").append(compareHist.bhattacharyya(source[0],target[0])).append("\r\n")
//                    .append("协方差:").append(compareHist.covariance(source[0],target[0])).append("\r\n")
//                    .append("相关性因子:").append(compareHist.ncc(source[0],target[0]));
//            Log.e("比对结果",sb.toString());
//            Log.e("1111",arrList.get(0));
//            Log.e("2222",arrList.get(1));
//            ToastUtil.show(ImgCompareActivity.this,sb.toString()+"list大小为："+arrList.size());

            if (TestNetActivity.isWiFiActive(ImgCompareFreActivity.this)) {
                if(compareHist.ncc(source[0],target[0])<Double.valueOf(matchdegree)){
                    NetUtil.sendAlarm2(b,this);
                    backToPre();
                }else{
                    backToPre();
                }
                File file = new File(arrList.get(0));
                file.delete();
            }else{
                if(compareHist.ncc(source[0],target[0])<Double.valueOf(matchdegree)){
                    Device device = DataSupport.findLast(Device.class);
                    Msg msg = new Msg();
                    msg.setDeviceno(device.getDeviceid());
                    msg.setImgurl(arrList.get(1));
                    msg.setChannelno("1");
                    msg.saveThrows();
                    backToPre();
                }else{
                    backToPre();
                }
            }

            if (TestNetActivity.isWiFiActive(ImgCompareFreActivity.this)) {
                List<Msg> msgs = DataSupport.findAll(Msg.class);
                if(msgs!=null&&msgs.size()>0){
                    for (int i = 0; i < msgs.size(); i++) {
                        Msg msg = msgs.get(i);
                        String imgurl = msg.getImgurl();
                        byte[] imgbytes = FileUtil.File2byte(imgurl);
                        if(imgbytes!=null){
                            if(msg.getChannelno().equals("0")){
                                NetUtil.sendAlarm1(imgbytes,this);
                            }else{
                                NetUtil.sendAlarm2(imgbytes,this);
                            }
                        }
                        DataSupport.delete(Msg.class,msg.getId());
                        File f = new File(imgurl);
                        f.delete();
                    }
                }
            }

        }catch (Exception e){
            e.printStackTrace();
        }
    }
    private  void backToPre(){
        MyApplication.getInstance().exit();
        Intent intent = new Intent(ImgCompareFreActivity.this, TakePhotoActivity.class);
        startActivity(intent);

    }
}
